package com.rock.upms.web.upms.controller;

import java.util.Date;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageInfo;
import com.rock.common.base.BaseController;
import com.rock.common.base.BaseQuery;
import com.rock.common.base.BaseResult;
import com.rock.common.util.AESUtil;
import com.rock.common.util.RockJsonUtil;
import com.rock.common.util.StringUtil;
import com.rock.upms.api.model.service.IUpmsDepartmentService;
import com.rock.upms.api.upms.service.IUpmsService;
import com.rock.upms.model.UpmsDepartment;
import com.rock.upms.model.UpmsDepartmentExample;
import com.rock.upms.model.UpmsDepartmentExample.Criteria;
import com.rock.upms.web.common.UpmsWebConfig;

@Controller
public class DeptController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(DeptController.class);
	@Autowired
	private IUpmsService upmsService;
	@Autowired
	private IUpmsDepartmentService upmsDepartmentService;

	// 跳转到机构列表展示页面预处理（初始化查询条件等系列操作）
	@ResponseBody
	public String getDeptList(HttpServletRequest request, HttpServletResponse response) {
		log.trace("获取部门列表json入参：");
		UpmsDepartmentExample upmsDepartmentExample = new UpmsDepartmentExample();
		upmsDepartmentExample.createCriteria().andCreateUsercodeIsNotNull();
		List<UpmsDepartment> list = upmsDepartmentService.selectByExample(upmsDepartmentExample);
		log.trace("获取部门列表json出参：" + RockJsonUtil.toJson(list));
		return RockJsonUtil.toJson(list);
	
	}
	
	
	// 跳转到机构列表展示页面预处理（初始化查询条件等系列操作）
	public String toListPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		/*
		 * 预处理：初始化查询条件
		 */
		log.trace("---->tolist-----------------------------------");
		BaseQuery query = new BaseQuery(1, UpmsWebConfig.getPageSize(), true);// 构造函数按默认分页方式分页，从第一页开始
		// Query query2=Query.noPagination();//不分页查询
		// query.add("tt", value)
		query.add("isDelete", "0");
		model.addAttribute("query", query);
		return "upms/dept/dept_list";
	}

	// 获取所有机构信息列表
	@ResponseBody
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@RequiresPermissions(value = "upms:dept:list")
	public BaseResult list(BaseQuery query, HttpServletRequest request, HttpServletResponse response) {
		// 测试 获取所有机构信息
		System.out.println(RockJsonUtil.toJson(query));
		int pageNum = query.getPageNum();// 页号
		int pageSize = query.getPageSize();// 每页显示记录数
		int navigatePages = UpmsWebConfig.getPageNavigatePages();// 导航显示页数
		if (!query.getIsPagination()) {
			pageSize = 0;// 不分页
		}
		// 封装查询条件
		String isDelete = (String) query.getExtend().get("isDeleted");// 是否删除
		String deptCode = (String) query.getExtend().get("deptCode");// 机构号
		String deptName = (String) query.getExtend().get("deptName");// 机构名模糊匹配
		String orderBy = " id asc ";// 默认ID升序
		UpmsDepartmentExample deptExample = new UpmsDepartmentExample();
		Criteria criteria = deptExample.or();
		if (StringUtil.isNotBlank(isDelete)) {
			criteria.andIsDeletedEqualTo(isDelete);
		}
		if (StringUtil.isNotBlank(deptCode)) {
			criteria.andDeptCodeEqualTo(deptCode);
		}
		if (StringUtil.isNotBlank(deptName)) {
			criteria.andDeptNameLike("%" + deptName + "%");
		}
		deptExample.setOrderByClause(orderBy);
		// startPage后面紧跟的这个查询就是一个分页查询
		System.out.println("================pageNum:" + pageNum);
		System.out.println("================pageSize:" + pageSize);
		System.out.println("================navigatePages:" + navigatePages);
		PageInfo<UpmsDepartment> page = upmsDepartmentService.selectByExampleForStartPage(deptExample, pageNum,
				pageSize, navigatePages);
		if (page != null) {
			// 遍历数据将ID加密后存放于reserved5 字段
			List<UpmsDepartment> list = page.getList();
			for (UpmsDepartment ouDepartment : list) {
				ouDepartment.setReserved5("");
			}
			return BaseResult.success("").add("pageInfo", page);
		} else {
			return BaseResult.fail("获取数据失败");
		}
	}

	// 查看机构信息
	@RequiresPermissions("upms:dept:read")
	@RequestMapping(value = "/read/{cryptId}", method = RequestMethod.GET)
	public String read(@PathVariable("cryptId") String cryptId, Model model) {
		UpmsDepartment vo = null;
		String salt = "";
		String id = AESUtil.getInstance().decrypt(salt, cryptId);
		if (StringUtil.isBlank(id)) {
			System.out.println("===================你操作的数据不存在!===================");
		} else {
			vo = (UpmsDepartment) upmsDepartmentService.selectByPrimaryKey(StringUtil.toInteger(id));
		}
		model.addAttribute("vo", vo);
		return "upms/dept/dept_read";
	}

	// 新增机构信息（初始化）
	@RequiresPermissions("upms:dept:add")
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Model model) {
		UpmsDepartment vo = new UpmsDepartment();
		vo.setCreateUsercode("");
		vo.setCreateUsername("");
		vo.setCreateTime(new Date());
		model.addAttribute("vo", vo);
		System.out.println("vo==============99999999999=====");
		return "upms/dept/dept_add";
	}

	// 新增机构信息（保存）
	@ResponseBody
	@RequiresPermissions("upms:dept:add")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public BaseResult add(UpmsDepartment vo, HttpServletRequest request, HttpServletResponse response, Model model) {
		System.out.println("vo===================" + vo.toString());
		vo.setCreateUsercode("");
		vo.setCreateUsername("");
		vo.setCreateTime(new Date());
		vo.setIsDeleted("0");
		System.out.println(vo.toString());
		int result = upmsDepartmentService.insert(vo); // upmsDepartmentService.insertUpmsDepartment(vo);
		if (result == 0) {
			log.error("=====保存失败：插入表异常");
			return BaseResult.fail("插入表异常");
		} else {
			return BaseResult.success("保存成功");
		}
	}

	// 删除机构
	@ResponseBody
	@RequiresPermissions("upms:dept:delete")
	@RequestMapping(value = "/delete/{cryptId}", method = RequestMethod.GET)
	public BaseResult delete(@PathVariable("cryptId") String cryptId, Model model) {
		String salt = "";
		String id = AESUtil.getInstance().decrypt(salt, cryptId);
		System.out.println("===================id===================" + id);
		if (StringUtil.isBlank(id)) {
			log.info("=====操作的数据不存在！");
			return BaseResult.fail("你操作的数据不存在");
		} else {
			int backint = upmsDepartmentService.deleteByPrimaryKey(StringUtil.toInteger(id));
			if (backint != 0) {
				return BaseResult.success("删除成功");
			} else {
				return BaseResult.fail("删除失败");
			}
		}
	}
}